<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\exception\LogicException;
use app\common\logic\category\Category;
use app\common\helper\util\Page;
use app\admin\logic\system\Log;
use app\exam\model\admin\ModuleRollupPaper as ModuleRollupPaperModel;
use think\annotation\Inject;

/**
 * Class ModuleRollupPaper
 *
 * @package app\exam\logic\admin
 */
class ModuleRollupPaper extends ModuleRollupPaperModel
{
    /**
     * @Inject()
     *
     * @var Category
     */
    protected $categoryLogic;

    /**
     * @Inject()
     *
     * @var Paper
     */
    protected $paperLogic;

    /**
     * @Inject()
     *
     * @var \app\exam\model\admin\ModuleRollup
     */
    protected $moduleRollup;

    /**
     * 获取试卷列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/3/2
     *
     * @param array $map
     * @param array $paperWhere
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $map = [], array $paperWhere = [])
    {
        return $this
            ->hasWhere('paper', $paperWhere)
            ->with(['paper'])
            ->where($map)
            ->paginate(Page::listRows())->each(function ($item) {
                $item->cate_title = $this->categoryLogic->parseTitle($item->category, 3);
            });
    }

    /**
     * 获取选择面板数据
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param int   $rollupId
     * @param array $map
     * @return \think\Paginator
     */
    public function getChooseList(int $rollupId, array $map = [])
    {
        $category = $this->moduleRollup->whereId($rollupId)->value('category');
        $map[]    = ['category', '=', $category];

        return $this->paperLogic
            ->where($map)
            ->withCount(['checked' => function($query) use ($rollupId)
            {
                $query->where('rollup_id', $rollupId);
            }])
            ->order('update_time', 'desc')
            ->append(['paper_type_text'])
            ->paginate(Page::listRows())
            ->each(function ($item) {
                $item->checked = !!$item->checked_count;
            });
    }

    /**
     * 新增绑定的试卷
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/4
     *
     * @param int   $moduleId
     * @param array $papers
     * @throws \Exception
     */
    public function createModuleRollupPaper(int $rollupId, array $papers)
    {
        $saveAll = [];
        foreach ($papers as $paper) {
            $saveAll[] = [
                'rollup_id' => $rollupId,
                'paper_id'  => $paper
            ];
        }

        $ret = $this->replace()->saveAll($saveAll);

        if (!$ret) {
            throw new LogicException('关联失败');
        }

        // 更新数量
        $num = count($ret);
        $this->moduleRollup->where('id', $rollupId)->inc('paper_count', $num)->update();

        Log::write('【套卷/' . $rollupId . '】新增绑定的试卷【 ' . implode(',', $papers) . '】', 'rollup', 'create', true);
    }

    /**
     * 移除试卷
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/3
     *
     * @param string $ids
     */
    public function deleteModuleRollupPaper(int $rollupId, string $ids)
    {
        $res = $this->whereIn('id', $ids)->selectOrFail()->delete();
        if (!$res) {
            throw new LogicException('移除失败');
        }

        $num = count(explode(',', $ids));

        $this->moduleRollup->where('id', $rollupId)->dec('paper_count', $num)->update();

        Log::write('【套卷/' . $rollupId . '】移除绑定的试卷【' . $ids . '】', 'rollup', 'delete', true);
    }

}